import fetch from 'dva/fetch';

function parseJSON(response) {
  const json = response.json();
  console.log('响应json', json);
  return json;
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, params) {
  console.log('请求', url, params);

  const body = Object.assign({}, params.body);

  const headers = Object.assign({}, {
    'Content-Type': 'application/json'
  }, params.headers);

  let method = {method: params.method ? params.method : 'POST'};

  let mode = {mode: params.mode ? params.mode : 'cors'};

  params = Object.assign({credentials: 'include'}, params, {body, headers}, mode, method);

  // 若是get请求重新处理请求参数
  if ((params.method === 'GET' || params.method === 'HEAD') && params.body) {
    url = assembling(url, params.body);
    delete params.body;
  } else {
    params.body = JSON.stringify(body);
  }

  return fetch(url, params)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => ({data}))
    .catch(err => ({err}));
}

/**
 * 把params 对象转成get请求参数(由&连接键值的字符串)
 * @param url
 * @param params
 * @returns {*}
 */
function assembling(url, params) {
  let keys = Object.keys(params);
  let query = [];

  keys.forEach((key, i) => {
    let value = params[key];
    if (value != null) {
      query.push(key + '=' + encodeURIComponent(value));
    }
  });

  if (url.lastIndexOf('?') > 0) {
    url = url + "&" + query.join('&');
  } else {
    url = url + "?" + query.join('&');
  }

  return url;
}
